<template>
  <h1>上传资源</h1>
  <br>
  <el-form ref="resourceForm" :model="form" label-width="auto" style="max-width: 600px" :rules="rules">
    <!-- 资源名 -->
    <el-form-item label="资源名" prop="resourceName">
      <el-input v-model="form.resourceName" />
    </el-form-item>
    <!-- 资源类型、是否快进 -->
    <el-row>
      <!-- 第一个表单项：占一定列宽 -->
      <el-col :span="12">
        <el-form-item label="资源类型">
          <el-switch
              v-model="form.isDocument"
              size="large"
              active-text="视频"
              inactive-text="文档"
              @change="resetForm"
          />
        </el-form-item>
      </el-col>
      <!-- 第二个表单项：占剩余列宽（条件渲染保持不变） -->
      <el-col :span="12">
        <el-form-item v-if="form.isDocument" label="是否快进">
          <el-radio-group v-model="form.isSpeed" size="large" fill="#6cf">
            <el-radio-button label="允许快进" :value=true />
            <el-radio-button label="禁止快进" :value=false />
          </el-radio-group>
        </el-form-item>
      </el-col>
    </el-row>
    <!-- 资源标签 -->
    <el-form-item label="资源标签" prop="tagId">
      <el-cascader
          placeholder="请选择资源标签"
          :options="tags"
          :props="props"
          clearable
          :clear-icon="CloseBold"
          v-model="form.tagId"
      />
    </el-form-item>
    <!-- 资源说明 -->
    <el-form-item label="资源说明">
      <el-input v-model="form.resourceDesc" />
    </el-form-item>
    <!-- 资源上传 -->
    <el-form-item label="资源上传">
      <div v-if="form.isDocument">
        <el-upload
            action="#"
            :auto-upload="false"
            accept="video/*"
            name="video"
            :on-exceed="handleExceed"
            :on-change="handleFileChange"
            :file-list="fileList"
            :limit="1"
        >
        <el-button type="primary">
          <el-icon class="mr-2"><VideoCamera /></el-icon> 视频上传
        </el-button>
        </el-upload>
      </div>
      <div v-if="!form.isDocument">
        <el-upload
            action="#"
            :auto-upload="false"
            accept=".pdf,.doc,.docx,.txt"
            name="video"
            :on-exceed="handleExceed"
            :on-change="handleFileChange"
            :file-list="fileList"
            :limit="1"
        >
          <el-button type="success">
            <el-icon class="mr-2"><Document /></el-icon> 文档上传
          </el-button>
        </el-upload>
      </div>
    </el-form-item>
    <!-- 功能按钮 -->
    <el-form-item>
      <el-button type="primary" @click="onSubmit">上传资源</el-button>
      <el-button @click="resetForm">重置表单</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { ElMessage, type UploadRawFile, type UploadStatus, type UploadFile } from "element-plus";
import {VideoDurationUtil} from '../../utils/videoHandle.ts'
import { VideoCamera, Document, CloseBold } from '@element-plus/icons-vue'
import request from "@/utils/request.ts";

// 定义表单数据类型接口
interface FormData {
  resourceName: string
  file: UploadRawFile | null  // 明确文件类型为原始文件或null
  isDocument: boolean  // true:视频, false:文档
  isSpeed: boolean  // 是否允许快进
  resourceTotalDuration: number
  resourceDesc:string
  tagId: number | null
  adminId: number
}

// 文件列表类型（使用element-plus提供的UploadFile类型）
const fileList = ref<UploadFile[]>([])

const resourceForm = ref()

// 表单数据（使用FormData接口约束）
const form = reactive<FormData>({
  resourceName: '',
  file: null,
  isDocument: false,
  isSpeed: true,
  resourceTotalDuration:0,
  resourceDesc:'',
  tagId:null,
  adminId:0,
})

// 定义表单验证规则接口
interface FormRules {
  resourceName: {
    required: boolean;
    message: string;
    trigger: string;
  }[];
  tagId: {
    required: boolean;
    message: string;
    trigger: string;
  }[];
}

// 定义验证规则
const rules = reactive<FormRules>({
  resourceName: [
    { required: true, message: '请输入资源名称', trigger: 'blur' },
  ],
  tagId: [
    { required: true, message: '请选择资源标签', trigger: 'change' }
  ]
})

const tags = ref([])

//级联选择器属性，选中后只显示最后一级节点的value
const props = {
  emitPath:false
}

//钩子函数
onMounted(() => {
  getTag();

})

//获得资源标签
const getTag = () => {
  request.post('/trainingTag/getTag').then(res => {
    tags.value = res.data.data
  })
}
// 文件超出限制处理函数
const handleExceed = () => {
  ElMessage.warning('只能上传一个文件')
}

// 文件变化处理函数（明确参数类型）
const handleFileChange = (file: UploadFile, files: UploadFile[]) => {
  // 确保类型安全，处理可能的undefined
  form.file = file.raw || null
  if(form.isDocument == true) {
    getResourceTotalDuration().then(duration => {
      //视频文件的显示时长1:06
      //console.log(duration?.fullFormat)
      //视频文件的具体时长(秒) 66.87
      //console.log(duration?.durationSeconds)
      //视频文件的具体时长(秒) 66
      //console.log(Math.floor(duration?.durationSeconds!))
      form.resourceTotalDuration = Math.floor(duration?.durationSeconds!)
    })
  } else {
    form.resourceTotalDuration = 0
  }
}

// 提交处理函数
const onSubmit = () => {
  //表单校验
  resourceForm.value.validate((valid: boolean) => {
    if (valid) {
      // 验证通过，检查文件是否存在
      if (!form.file) {
        ElMessage.error('请选择要上传的文件');
        return;
      }
      //文件大小验证
      const fileSize = form.file.size / 1024 / 1024; // 转换为MB
      if (form.isDocument && fileSize > 500) { // 视频最大500MB
        ElMessage.error('视频文件大小不能超过500MB');
        return;
      }
      if (!form.isDocument && fileSize > 500) { // 文档最大500MB
        ElMessage.error('文档文件大小不能超过500MB');
        return;
      }

      // 所有验证通过，执行提交逻辑
      console.log('表单验证通过，准备提交', form);
      form.adminId = JSON.parse(localStorage.getItem('admin')!).id;
      submitFormData();
    } else {
      ElMessage.error('表单验证失败，请检查填写内容');
      return false;
    }
  })
}

//提交逻辑
const submitFormData = async () => {
  const formData = new FormData();
  // 添加文件
  if (form.file) {
    formData.append('file', form.file);
  }
  // 2. 单独添加每个表单字段
  formData.append('resourceName', form.resourceName);
  formData.append('isDocument', form.isDocument.toString());
  formData.append('isSpeed', form.isSpeed.toString());
  formData.append('resourceTotalDuration', form.resourceTotalDuration.toString());
  formData.append('resourceDesc', form.resourceDesc);
  formData.append('tagId', form.tagId?.toString() || ''); // 处理可能的null
  formData.append('adminId', form.adminId.toString());
  request.post('/trainingResource/insert', formData,
      {
        headers: { 'Content-Type': 'multipart/form-data' }
      }).then((res) => {
    //保存或者上传成功后执行语句
    console.log(res);
    resetForm();
  })
}

//重置表单
const resetForm = () => {
  resourceForm.value.resetFields();
  form.resourceName = ''
  form.file = null
  form.isSpeed = true
  form.resourceTotalDuration = 0
  form.resourceDesc = ''
  form.tagId = null
}

//获取视频文件时长
const getResourceTotalDuration = async () => {
  try {
    // 先判断文件是否存在
    if (!form.file) {
      ElMessage.error('请先选择视频文件');
      return;
    }
    // 1. 获取视频时长（秒）
    const durationSeconds = await VideoDurationUtil.getDuration(form.file);

    // 2. 格式化时长（多种格式示例）
    const fullFormat = VideoDurationUtil.format(durationSeconds); // 如 "01:02:30"

    return {fullFormat, durationSeconds}
  } catch (err) {
    // 4. 解析错误并显示
    const error = VideoDurationUtil.parseError(err);
    ElMessage.error(`错误：${error.message}`);
    // 可根据错误类型做特殊处理
    if (error.type === VideoDurationUtil.ErrorType.NOT_VIDEO_FILE) {
      alert('请选择视频文件（如MP4、WebM等）');
    }
  }
}
</script>

<style scoped>

</style>